import React, { useState, useEffect, useRef } from "react";
import SearchContent from "./components/SearchContent";
import TableContent from "./components/TableContent";
import CommonLoading from "@/components/CommonLoading";
import GroupContent from "./components/GroupContent";
import CreatGroupModal from "./components/CreatGroupModal";
import AddToGroup from "./components/AddToGroup";
import { Button, message, Modal, Dropdown, Menu } from "antd";
import {
	gtEcstoregroupList,
	ecstoregroupSave,
	ecstoregroupDelete,
	ecstoregroupUpdateName,
	addEcstoregroup,
	createExportTask,
	generateRulesConfig,
	querySelectPlatformType,
	getAuthMessage,
	getWeChatShopAgainAuth
} from "./service";
import { isEmpty } from "lodash";
import AuthorizeStoreModal from "./components/AuthorizeStore";
import styles from "./components/index.module.less";
import { getSearchParamsObj } from "@/utils/utils.jsx";
import { getAuthMsg, removeAuthMsg, getCurrentUser } from "@/utils/authority";
import { useLocation, useNavigate } from "react-router-dom";
import { FileTextOutlined } from "@ant-design/icons";
import OtherModifyRecordModal from "./components/OtherModifyRecordModal/index";
import ExportModal from "./components/ExportModal";
import AuthorizeInfo from "./components/AuthorizeInfo";
import { useResize } from '@/hooks/useResize';
import moment from "moment";

const StoreManage = () => {
	const [query, setQuery] = useState({});
	const [visible, setVisible] = useState(false);
	const [groupList, setGroupList] = useState([]); //分组数据
	const [groupItem, setGroupItem] = useState({}); //当前的分组item
	const [tableItem, setTableItem] = useState({}); //当前table的item
	const [taskId, setTaskId] = useState(""); //导出任务id
	const [platformList, setPlatformList] = useState([]); //所属平台下拉
	const [loading, setLoading] = useState(false);
	const [updateKey, setUpdateKey] = useState();

  //监听变更
  const { el: headerEl, height: headerHeight } = useResize();
	const parentRef = useRef();
	const stageParams = useRef({});

	const navigate = useNavigate();
	const location = useLocation();

	useEffect(() => {
		handleGtEcstoregroupList();
		getSelectPlatformType();
	}, []);

	useEffect(() => {
		//检测是否是授权回调
		if (getAuthMsg()) {
			//反授权
			handleAuthBack();
		} else {
			//url回掉
			handleAuthorize(location, navigate);
		}
	}, []);

	const handleAuthBack = async () => {
		const msg = JSON.parse(getAuthMsg());
		const obj = getCurrentUser() || {};
		setLoading(true);
		const res = await getAuthMessage({
			...msg,
			userName: obj.account,
			uuid: obj.uuid
		});
		setLoading(false);
		removeAuthMsg();
		if (res.status == 1) {
			//授权成功回调
			Modal.success({
				title: "授权成功",
				content: (
					<div>
						<p>授权成功</p>
					</div>
				)
			});
		} else {
			Modal.error({
				title: "授权失败",
				content: (
					<div>
						<p>错误信息：{res.data}</p>
						<p>{res.errorCode}</p>
					</div>
				)
			});
		}
	};

	//店铺授权回调展示
	const handleAuthorize = (location, navigate) => {
		const obj = getSearchParamsObj(location.search);
		if (obj.authState && obj.msg) {
			navigate("/views/basic/qimenStore");
			if (obj.authState == 1) {
				//授权成功回调
				Modal.success({
					title: "授权成功",
					content: (
						<div>
							<p>
								1、授权成功，授权时间 {moment(Date.now()).format("YYYY-MM-DD HH:mm:ss")}，有效期至{" "}
								{moment(obj.msg * 1000).format("YYYY-MM-DD HH:mm:ss")}
							</p>
							<p>2、授权内容：同步店铺商品，同步店铺订单</p>
						</div>
					)
				});
			} else {
				Modal.error({
					title: "授权失败",
					content: (
						<div>
							<p className="textOverflowMulti">错误信息：{obj.msg}</p>
							<p>如有疑问，请联系客服</p>
						</div>
					)
				});
			}
		}
	};

	//获取店铺
	const getSelectPlatformType = async () => {
		setLoading(true);
		const { data = [], success } = await querySelectPlatformType();
		if (success) {
			setPlatformList(data);
		}
		setLoading(false);
	};

	//获取分组数据
	const handleGtEcstoregroupList = async () => {
		setLoading(true);
		const { data = [], success } = await gtEcstoregroupList();
		if (success) {
			// setData(records);
			setGroupList(data);
		}
		setLoading(false);
	};

	//创建/重命名分组
	const handleSaveGroup = async (val, closeVisible = true) => {
		setLoading(true);
		let res;
		if (!isEmpty(groupItem)) {
			//编辑
			res = await ecstoregroupUpdateName({
				...val,
				id: groupItem.id
			});
		} else {
			console.log("handleSaveGroup", parentRef);
			//创建
			res = await ecstoregroupSave({
				...val,
				ecStoreIds: !isEmpty(parentRef.current.recordData)
					? [parentRef.current.recordData.id]
					: parentRef.current.tableList.map(item => item.id)
			});
		}
		const { msg = "", success } = res;
		if (success) {
			message.success(msg);
			handleGtEcstoregroupList();
			if (closeVisible) {
				setVisible(false);
			}
		}
		setLoading(false);
	};

	//添加至分组
	const handleAddToGroup = async val => {
		setLoading(true);
		const { data = [], success } = await addEcstoregroup({
			...val,
			ecStoreId: tableItem.id
		});
		if (success) {
			// setData(records);
			handleGtEcstoregroupList();
			setVisible(false);
		}
		setLoading(false);
	};

	//删除分组
	const handleDeleteGroup = async val => {
		setLoading(true);
		const { msg = "", success } = await ecstoregroupDelete({
			id: val.id
		});
		if (success) {
			message.success(msg);
			handleGtEcstoregroupList();
			setVisible(false);
		}
		setLoading(false);
	};

	//点击添加店铺
	const handAddStore = async () => {
		setLoading(true);
		const { data = {}, success } = await generateRulesConfig();
		if (success) {
			if (data && !isEmpty(data)) {
				setVisible("author");
			} else {
				setVisible("authorize");
			}
		}
		setLoading(false);
	};

	//微信视频号小店重新授权
	const handleWeChatShopAgainAuth = async (id) => {
		setLoading(true);
		const { success, msg } = await getWeChatShopAgainAuth({ id });
		if (success) {
			message.success(msg);
			handleGtEcstoregroupList();
			setUpdateKey(Date.now());
		} else if (success == false) {
			message.error(msg);
		}
		setLoading(false);
	}

	//创建导出任务
	const handleCreateExportTask = async params => {
		setLoading(true);
		const { data, success } = await createExportTask(params);
		if (success) {
			setTaskId(data);
			setVisible("export");
		}
		setLoading(false);
	};

	//导出
	const handleExport = type => {
		const params = {
			businessParam: {},
			taskType: 3009
		};
		if (type == 1) {
			params.businessParam = JSON.stringify({});
		} else if (type == 2) {
			params.businessParam = JSON.stringify(parentRef.current.exportParams.current);
		} else {
			if (parentRef.current.selectRowKeys.length == 0) {
				return message.info("请勾选店铺");
			}
			params.businessParam = JSON.stringify({
				storePkList: parentRef.current.selectRowKeys
			});
		}
		handleCreateExportTask(params);
	};

	//导出进度弹窗
	const ExportModalProps = {
		taskId,
		visible: visible == "export",
		handleCancel() {
			setVisible(false);
			setTaskId("");
		}
	};

	//创建分组弹窗
	const CreatGroupModalProps = {
		visible: visible == "create",
		item: groupItem,
		handleCancel() {
			setVisible(false);
			setGroupItem({});
		},
		hanleOk(val) {
			handleSaveGroup(val);
		}
	};

	//分组设置
	const AddToGroupProps = {
		visible: visible == "group",
		groupList,
		handleCancel() {
			setVisible(false);
		},
		hanleOk(val) {
			handleAddToGroup(val);
		},
		CreateGroup(val) {
			handleSaveGroup(val, false);
		}
	};

	//顶部分组
	const GroupContentProps = {
		groupList,
		handleDeleteGroup,
		query,
		handleSetQuery(val) {
			setQuery({
				...val
			});
		},
		handleEditGroup(item) {
			setGroupItem(item);
			setVisible("create");
		}
	};

	//店铺授权
	const AuthorizeStoreModalProps = {
		visible: visible == "author",
		shopPlatform: stageParams.current?.shopPlatform,
		handleCancel() {
			setVisible(false);
		}
	};

	//查看日志
	const OtherModifyRecordModalProps = {
		visible: visible == "otherConfig",
		handleCancel() {
			setVisible(false);
		}
	};

	//授权店铺之前的弹窗提示
	const AuthorizeInfoProps = {
		visible: visible == "authorize",
		handleCancel() {
			setVisible(false);
		}
	};

	const searchProps = {
		query,
		platformList,
		handleCreateGroup() {
			if (isEmpty(query)) {
				return message.info("请重新筛选后创建店铺");
			}
			if (parentRef.current.tableList.length == 0) {
				return message.info("当前筛选条件下无店铺数据，请重新筛选后创建店铺");
			}
			setVisible("create");
		},
		handleSearch(val) {
			if (val && Object.keys(val)?.length) {
				setQuery(val);
			} else {
				setQuery({});
			}
		}
	};

	const tableProps = {
		query,
		headerHeight,
		updateKey,
		groupConfig(record) {
			setVisible("group");
			setTableItem(record);
		},
		handleClick(type, id, flag) {
			if (type == 25) {
				//视频号小店
				handleWeChatShopAgainAuth(id);
			} else {
				stageParams.current.shopPlatform = flag;
				// setVisible("author");
				handAddStore();
			}
		}
	};

	return (
		<>
			<div ref={headerEl}>
				<div style={{ marginBottom: '16px'}} className="global-page-wrap">
					<GroupContent {...GroupContentProps} />
				</div>
				<SearchContent {...searchProps} />
			</div>
			<div className="global-page-wrap">
				<div className={styles.btnWrapper}>
					<Button
						className={styles.btnItem}
						onClick={() => {
							handAddStore();
						}}
						type="primary"
					>
						添加店铺
					</Button>
					<Dropdown
						trigger="hover"
						overlay={
							<Menu>
								<Menu.Item key="1" onClick={() => handleExport("1")}>
									导出所有店铺信息
								</Menu.Item>
								<Menu.Item key="2" onClick={() => handleExport("2")}>
									导出筛选后的店铺信息
								</Menu.Item>
								<Menu.Item key="3" onClick={() => handleExport("3")}>
									导出已勾选的店铺信息
								</Menu.Item>
							</Menu>
						}
					>
						<Button className={styles.btnItem}>导出店铺信息</Button>
					</Dropdown>
					<div
						style={{ marginLeft: "auto" }}
						onClick={() => {
							setVisible("otherConfig");
						}}
						className={styles.createStore}
					>
						<FileTextOutlined className="main-color" />
						<span className="line-height-21" style={{ marginLeft: "6px" }}>
							查看日志
						</span>
					</div>
				</div>
				<TableContent ref={parentRef} {...tableProps} />
			</div>

			<CreatGroupModal {...CreatGroupModalProps} />
			<AddToGroup {...AddToGroupProps} />
			<AuthorizeStoreModal {...AuthorizeStoreModalProps} />
			{visible == "otherConfig" && <OtherModifyRecordModal {...OtherModifyRecordModalProps} />}
			{visible == "export" && <ExportModal {...ExportModalProps} />}
			<AuthorizeInfo {...AuthorizeInfoProps} />
			<CommonLoading loading={loading} />
		</>
	);
};

export default React.memo(StoreManage, () => {
	return true;
});
